/*Copyright(C) 2009 Careil Baptiste

This program is free software; you can redistribute it and / or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU

Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software

Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110 - 1301 USA
*/

#include "../headers.h"

int raw_read(char *chaine, int curseur, int longueur, int (*restrict)(int), int ret_on_touche_dir) {
	int len = curseur, cur = curseur, key = 0;
	attr_t attr;
	short pair;

	if(chaine == NULL || longueur <= 0 || curseur > longueur || curseur < 0) {
		return 0;
	}

	attr_get(&attr, &pair, NULL);
	curs_set(1);

	if(cur > 0) {
		addnstr(chaine, cur);
	}

	while(key != KEY_RETURN) {
		key = getch();

		if(ret_on_touche_dir && (key == touche_gauche || key == touche_droite)) {
			return key;
		}
		else if(key == M_KEY_BACKSPACE  || key == M_KEY_DELETE) {
			if((key == M_KEY_BACKSPACE && cur > 0) || (key == M_KEY_DELETE && cur < len && len > 0)) {
				if(key == M_KEY_BACKSPACE) {
					pmove(GAUCHE, 1);
					cur--;
				}
				if(cur < len) {
					memmove(&chaine[cur], &chaine[cur + 1], len - cur - 1);
				}
				len--;
				addnstr(&chaine[cur], len - cur);
				attr_set(attr, 0, 0);
				addch(' ');
				attr_set(attr, pair, 0);
				pmove(GAUCHE, len - cur + 1);
			}
		}
		else if(key == KEY_LEFT) {
			if(cur > 0) {
				pmove(GAUCHE, 1);
				cur--;
			}
		}
		else if(key == KEY_RIGHT) {
			if(cur < len) {
				pmove(DROITE, 1);
				cur++;
			}
		}
		else if(len < longueur - 1 && (restrict == NULL || restrict(key))) {
			if(cur < len) {
				memmove(&chaine[cur + 1], &chaine[cur], len - cur);
			}
			chaine[cur] = key;
			addnstr(&chaine[cur], len - cur + 1);
			pmove(GAUCHE, len - cur);
			len++;
			cur++;
		}
		refresh();
	}

	chaine[len] = '\0';

	curs_set(0);
	return (len);
}

int lire(char *chaine, int longueur) {
	CSLP_ColorText(CS);
	return raw_read(chaine, 0, longueur, isprint, 0);
}

long lire_long(void) {
	char nombreTexte[12] = {0};

	CSLP_ColorText(CS);
	raw_read(nombreTexte, 0, 12, isdigit, 0);

	return strtol(nombreTexte, NULL, 10);
}

int lire_menu(void) {
	char nombreTexte[12] = {0};
	int key;

	CSLP_ColorText(CS);
	key = raw_read(nombreTexte, 0, 12, isdigit, 1);

	if(key == touche_gauche || key == touche_droite) {
		return key;
	}
	return strtol(nombreTexte, NULL, 10);
}
